<template>
	<view class="merchant-list">
		<u-navbar class="navbar" :is-back="false" :is-fixed="true">
			<search style="width: 100%" @confirm="merchantList" />
		</u-navbar>
		<view class="p-2">
			<block v-for="(item,index) in shopList">
				<MerchantCardVue :item="item"></MerchantCardVue>
			</block>
		</view>
	</view>
</template>

<script>
	import {
		merchantList
	} from "@/api/goods.js";

	import MerchantCardVue from './template/tpl_merchant_card.vue';
	import Search from './template/tpl_search.vue';

	export default {
		components: {
			Search,
			MerchantCardVue
		},
		data() {
			return {
				page: 1,
				shopList: [],
				tempList: [],
				areaTree: []
			}
		},
		onReachBottom() {
			if (this.tempList.length < 10) return
			this.page++;
			this.loadData();
		},
		created() {
			this.areaTree = uni.getStorageSync('areaTree') || []
			this.merchantList()
		},
		methods: {
			merchantList(keyword) {
				const data = {
					page: this.page,
					limit: 10
				}
				if (keyword) {
					data.keyword = keyword
				}
				uni.showLoading()
				merchantList(data).then(res => {
					const list = res.data.data.list || []
					this.tempList = list
					list.forEach(item => {
						const ids = item.merchant_address.split(',')
						const areaFlat = this.flattenAreaTreeRecursive(this.areaTree);
						const pathStr = areaFlat.filter(a => ids.includes(a.value + '')).map(a => a.label).join(
							'')
						item.address = pathStr
					})
					if (this.page === 1) {
						this.shopList = list
					} else {
						this.shopList = this.shopList.concat(list)
					}
				}).finally(() => {
					uni.hideLoading()
				})
			},
			flattenAreaTreeRecursive(tree, result = [], parentId = null) {
				// 遍历当前层级的每个节点
				tree.forEach(node => {
					// 复制节点并添加父级ID（可选）
					const item = {
						...node,
						parentId
					};
					// 添加到结果数组
					result.push(item);

					// 如果有子节点，递归处理
					if (node.children && node.children.length > 0) {
						this.flattenAreaTreeRecursive(node.children, result, node.value);
					}
				});

				return result;
			},
		}
	}
</script>

<style lang="scss">
	.merchant-list {}
</style>